import { Controller, Get, Post, Body, Patch, Param, Delete, HttpCode, HttpStatus, UseGuards } from '@nestjs/common'
import { UserEntity } from '@/modules/user/entities/user.entity'
import { UserService } from './user.service'
import { CreateUserDto } from './dto/create-user.dto'
import { UpdateUserDto } from './dto/update-user.dto'
import { ConfigService } from '@nestjs/config'
import { ApiResponse } from '@nestjs/swagger'
import { IParamsResult, ListParams } from '@/shared/core/decorator/ListParams.decorator'
import { RoleService } from '../role/role.service'
import { AuthGuard } from '@nestjs/passport'

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService, private readonly configService: ConfigService, private readonly roleService: RoleService) {}

  /**
   * 用户注册
   * @param createUserDto
   * @returns
   */
  @ApiResponse({ status: 201, description: '创建用户', type: [UserEntity] })
  @Post('register')
  @HttpCode(HttpStatus.CREATED)
  create(@Body() createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto)
  }

  @Get('getTestName')
  getTestName() {
    return this.configService.get('DB').database
  }

  @UseGuards(AuthGuard('jwt'))
  @Get()
  async findAll(@ListParams({ where: ['username'], order: { id: 'DESC' } }) params: IParamsResult) {
    const [rows, total] = await this.userService.findAll(params)
    const { pageParams } = params

    return {
      rows,
      page: { total, ...pageParams },
    }
  }

  // 退出
  @Get('logout')
  async logout() {
    return {
      name: '',
    }
  }

  @Get(':id')
  async findOne(@Param('id') id: string) {
    return await this.userService.findOne(+id)
  }

  @Get('router/:id')
  async findRouter(@Param('id') id: string) {
    const user = await this.findOne(id)
    const result = await this.roleService.findOne(user.roles[0].id)
    return { ...user, ...result }
  }

  @UseGuards(AuthGuard('jwt'))
  // 修改密码
  @Patch('password/:id')
  updatePassword(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.userService.updatePassword(+id, updateUserDto)
  }

  @UseGuards(AuthGuard('jwt'))
  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.userService.update(+id, updateUserDto)
  }

  @UseGuards(AuthGuard('jwt'))
  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.userService.remove(+id)
  }
}
